#! python3
# -*- coding:utf-8 -*-
"""
" ip2region python api test
"
" Autho: Heanny<lzh@heanny.cn>
" Date : 2019-01-01
"""
import time
from python.ip2Region import Ip2Region


def GetIpRegion(ips, algorithm="b-tree"):
    '''三种查询方法'''
    algorithms = ["binary", "b-tree", "memory"]
    try:
        algorithms.index(algorithm)
    except Exception as e:
        algorithm = "b-tree"
    dbFile = "./data/ip2region.db"
    searcher = Ip2Region(dbFile)
    ReData = {}
    for ip in ips:
        try:
            sTime = time.time() * 1000
            if algorithm == "binary":
                data = searcher.binarySearch(ip)
            elif algorithm == "memory":
                data = searcher.memorySearch(ip)
            else:
                data = searcher.btreeSearch(ip)
            eTime = time.time() * 1000
            data['time'] = eTime - sTime
            ReData[ip] = data
            print("%s|%s in %5f ms" % (data["city_id"], data["region"].decode('utf-8'), eTime - sTime))
        except Exception as e:
            print("[Error]: %s" % e)
            ReData[ip] = {}
    searcher.close()
    return ReData


if __name__ == '__main__':
    GetIpRegion(['183.131.1.101', '2.2.2.2', '3.3.3.3'])
